package com.kaoyaya.delivery.activity;

import android.app.Dialog;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import com.googlecode.androidannotations.annotations.AfterViews;
import com.googlecode.androidannotations.annotations.Bean;
import com.googlecode.androidannotations.annotations.Click;
import com.googlecode.androidannotations.annotations.EActivity;
import com.googlecode.androidannotations.annotations.NoTitle;
import com.googlecode.androidannotations.annotations.ViewById;
import com.googlecode.androidannotations.annotations.sharedpreferences.Pref;
import com.kaoyaya.delivery.data.DataHelper;
import com.kaoyaya.delivery.data.InfoFile_;
import com.kaoyaya.delivery.data.entity.UserInfo;
import com.kaoyaya.util.CommUtil;
import com.kaoyaya.util.StringUtil;

/**
 * 用户登录
 * @author yubin
 * @data 2013-5-25
 */
@NoTitle
@EActivity(R.layout.activity_userlogin)
public class UserLoginActivity extends BaseActivity {

	@ViewById TextView tvTitle;
	@ViewById Button btnLogin;
	@ViewById EditText etUsername, etPassword;
	@Bean DataHelper dataHelper;
	@Pref InfoFile_ infoFile;
	Dialog pgDialog;
	final int IS_LOGIN = 0;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
	}
	
	@AfterViews
	void initView() {
		tvTitle.setText("考呀呀APP发货平台");
		dataHelper.setCallbackHandler(callbackHandler);
	}

	@Click
	void btnLogin() {
		String username = etUsername.getText().toString();
		String password = etPassword.getText().toString();
		if (StringUtil.isNotTrimBlanks(username, password)) {
			pgDialog = CommUtil.createLoadingDialog(context, "登陆中,请稍等...");
			dataHelper.login(IS_LOGIN, username, password);
		} else {
			showToast("用户名或者密码不能为空！");
		}
	}
	
	Handler callbackHandler = new Handler() {
		public void handleMessage(Message msg) {
			Object result = msg.obj;
			switch (msg.what) {
			case IS_LOGIN:
				UserInfo userInfo = (UserInfo) result;
				if (userInfo != null) {
					if (userInfo.getResultCode() == 1) {
						infoFile.edit().isAutoLogin().put(true).username().put(etUsername.getText().toString()).password().put(etPassword.getText().toString())
								.userId().put(userInfo.getUserId()).realname().put(userInfo.getRealName()).mobile().put(userInfo.getMobile()).email()
								.put(userInfo.getEmail()).apply();
						startActivity(new Intent(context, SlidingActivity.class));
						finish();
					}
					showToast(userInfo.getResultMessage());
				}
				break;
			}
			if (pgDialog != null) {
				pgDialog.cancel();
			}
		}
	};
	
}
